import React, { PureComponent, Fragment } from 'react';
import { connect } from 'dva';
import moment from 'moment';
import lscache from 'lscache';
import router from 'umi/router';

import {
    message,
    Row,
    Col,
    Icon,
    Card,
    Form,
    Modal,
    InputNumber,
    Input,
    Select,
    Button,
    Divider,
    Avatar,
    Radio,
    DatePicker,
    Pagination,
} from 'antd';
const { TextArea } = Input;
const { RangePicker } = DatePicker;
import StandardTable from '@/components/StandardTable1';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';

import styles from '@/pages/List/TableList.less';

const FormItem = Form.Item;
const { Option } = Select;
const getValue = obj =>
    Object.keys(obj)
        .map(key => obj[key])
        .join(',');

@Form.create()

/* eslint react/no-multi-comp:0 */
@connect(({ user, CreateNotice, deleteNotice, updateNotice, pagednotice, loading }) => ({
    currentUser: user.currentUser,
    pagednotice,
    updateNotice,
    CreateNotice,
    deleteNotice,
    loading: loading.models.pagednotice,
    currentUserLoading: loading.effects['user/fetchCurrent'],
    projectLoading: loading.effects['project/fetchNotice'],
    activitiesLoading: loading.effects['activities/fetchListList'],
}))
class pagednotice extends PureComponent {

    state = {
        expandForm: false,
        selectedRows: [],
        pagednoticeData: [],
        formValues: {},
        current: 1,
        pageSize: 10,
        visible: false,
        Rbnotice: 0,
        headline: null,
        details: null
    };

    columns = [
        {
            title: '标题',
            dataIndex: 'title',
        },

        {
            title: '发布时间',
            dataIndex: 'creationTime',
            // sorter: true,
            render: val => <span>{moment(val).format('YYYY-MM-DD HH:mm:ss')}</span>,
            // needTotal: true,
        },
        {
            title: '类型',

            dataIndex: 'noticeType',
            // eslint-disable-next-line no-nested-ternary
            render: val => <span>{val === 0 ? "优惠" : (val === 1 ? "提醒" : (val === 2 ? "消息" : "优惠"))}</span>,

        },
        {
            title: '操作',
            render: (text, record) => (
                <Fragment>
                    <a onClick={() => this.handleDleChange(record)}>删除</a>
                    <Divider type="vertical" />
                    <a onClick={() => this.handleModifyChange(record)}>修改</a>
                </Fragment>
            ),
        },
    ];
    componentDidMount() {
        let root = this;
        const headline = this.props;
        console.log(headline + '_____________');
        console.log('componentDidMount')
        const { current, pageSize } = this.state;
        const { userInfo } = this.props;
        this.state.userInfo = lscache.get('userInfo')
        if (this.state.userInfo) {
        } else {
            router.push("/user")
        }
        const { dispatch, form } = this.props;
        form.validateFields((err, fieldsValue) => {
            if (err) return;
            const values = {
                ...fieldsValue,
                skipCount: (current - 1) * pageSize,
                maxResultCount: pageSize,
                updatedAt: fieldsValue.updatedAt && fieldsValue.updatedAt.valueOf(),
            };
            this.setState({
                formValues: values,
            });
            dispatch({
                type: 'pagednotice/pagednotice1',
                payload: values,
            });
        });
        const values = {
            skipCount: (current - 1) * pageSize,
            maxResultCount: 10,
        };
        dispatch({
            type: 'pagednotice/pagednotice1',
            payload: values,
            callback: response => {
                if (response.success === true) {
                    this.state.getRoomData = response.result.items

                }
            }
        });

    }

    handleStandardTableChange = (pagination, filtersArg, sorter) => {
        // this.forceUpdate();
        console.log('handleStandardTableChange')
        const { dispatch } = this.props;

        const { formValues, status } = this.state;
        const filters = Object.keys(filtersArg).reduce((obj, key) => {

            const newObj = { ...obj };
            newObj[key] = getValue(filtersArg[key]);
            return newObj;
        }, {});
        const params = {
            skipCount: (pagination.current - 1) * pagination.pageSize,
            maxResultCount: pagination.pageSize,
            ...formValues,
            ...filters,
        };
        console.log(params)
        params.skipCount = (pagination.current - 1) * pagination.pageSize
        console.log('____________params')
        if (sorter.field) {
            let sorters = `${sorter.order}`
            if (sorters === 'ascend') {
                sorters = 'orderTime'
            } else if (sorters === 'descend') {
                sorters = 'orderTime\ndesc'
            } else {
                sorters = ''
            }
            params.Sorting = sorters;
        }


        dispatch({
            type: 'pagednotice/pagednotice1',
            payload: {
                ...params,
                status,
            }
        });
    };

    handleSelectRows = rows => {
        this.setState({
            selectedRows: rows,
        });
    };

    handleSearch = e => {
        console.log('handleSearch')
        e.preventDefault();
        const { dispatch, form } = this.props;
        const { status } = this.state;
        form.validateFields((err, fieldsValue) => {
            if (err) return;

            const values = {
                ...fieldsValue,
                status,
                updatedAt: fieldsValue.updatedAt && fieldsValue.updatedAt.valueOf(),
            };

            this.setState({
                formValues: values,
            });
            dispatch({
                type: 'pagednotice/pagednotice1',
                payload: values,
            });
        });
    };

    handleUpdatecheckIn = (flag, record) => {
        console.log('handleUpdatecheckIn')
        const { dispatch, form } = this.props;
        const { status } = this.state;
        const params = {
            id: record.id,
        };
        dispatch({
            type: 'checkinorder/checkinorder1',
            payload: params,
            callback: response => {
                form.validateFields((err, fieldsValue) => {
                    if (err) return;
                    const values = {
                        ...fieldsValue,
                        status,
                        updatedAt: fieldsValue.updatedAt && fieldsValue.updatedAt.valueOf(),
                    };
                    this.setState({
                        formValues: values,
                    });
                    dispatch({
                        type: 'pagednotice/pagednotice1',
                        payload: values,
                    });
                });
            }
        });
    }
    handleUpdateModalVisible = (flag, record) => {
        console.log('handleUpdateModalVisible')
        const { dispatch, form } = this.props;
        const { status } = this.state;
        const params = {
            id: record.id,
        };
        dispatch({
            type: 'order/order1',
            payload: params,
            callback: response => {
                form.validateFields((err, fieldsValue) => {
                    if (err) return;
                    const values = {
                        ...fieldsValue,
                        status,
                        updatedAt: fieldsValue.updatedAt && fieldsValue.updatedAt.valueOf(),
                    };
                    this.setState({
                        formValues: values,
                    });
                    dispatch({
                        type: 'pagednotice/pagednotice1',
                        payload: values,
                    });
                });
            }
        });

    };
    handleCreate = (flag) => {
        this.setState({
            headline: '',
            details: '',
            Rbnotice: 0,
            ids: 0,
            notice: '创建公告',
            visible: true
        })
    }
    handleDleChange = (record) => {

        const { dispatch,form } = this.props;
        const params = {
            id: record.id,
        };
        dispatch({
            type: 'deleteNotice/deleteNotice1',
            payload: params,
            callback: response => {
                if (response.success === true) {
                    console.log('__________成功')
                    message.success('删除成功');
                    form.validateFields((err, fieldsValue) => {
                        if (err) return;
                        const values = {
                            ...fieldsValue,
                            status,
                            updatedAt: fieldsValue.updatedAt && fieldsValue.updatedAt.valueOf(),
                        };
                        this.setState({
                            formValues: values,
                        });
                        dispatch({
                            type: 'pagednotice/pagednotice1',
                            payload: values,
                        });
                    });
                }
            }
        });
    }
    handleModifyChange = (record) => {
        let root = this;
        this.forceUpdate()
        console.log(record)
        root.setState({
            ids: record.id,
            Rbnotice: record.noticeType,
            notice: '修改公告',
            headline: record.title,
            details: record.content,
            visible: true
        }, function () {
            console.log(this.state.Rbnotice)
            console.log(this.state.headline)
            console.log(this.state.details)
        });
        this.forceUpdate()


    }
    handleOk = e => {


        if (this.state.headline) {
            if (this.state.details) {
                this.submitOK();
            } else {
                message.error('请输入内容');
            }
        } else {
            message.error('请输入标题');
        }



    }
    submitOK = () => {
        const { dispatch,form } = this.props;
        if (this.state.ids) {
            const { dispatch } = this.props;
            const params = {
                id: this.state.ids,
                logo: this.state.Rbnotice === 1 ? "https://cnd2.yeseesports.com//file/2019070203.png" :
                    (this.state.Rbnotice === 2 ? "https://cnd2.yeseesports.com//file/2019070205.png"
                        : "https://cnd2.yeseesports.com//file/2019070206.png"),
                noticeType: this.state.Rbnotice ? this.state.Rbnotice : 0,
                title: this.state.headline,
                content: this.state.details,
            };
            dispatch({
                type: 'updateNotice/updateNotice1',
                payload: params,
                callback: response => {
                    if (response.success === true) {
                        console.log('__________成功')
                        message.success('修改成功');
                        this.setState({
                            visible: false
                        })
                        form.validateFields((err, fieldsValue) => {
                            if (err) return;
                            const values = {
                                ...fieldsValue,
                                status,
                                updatedAt: fieldsValue.updatedAt && fieldsValue.updatedAt.valueOf(),
                            };
                            this.setState({
                                formValues: values,
                            });
                            dispatch({
                                type: 'pagednotice/pagednotice1',
                                payload: values,
                            });
                        });
                    }
                }
            });
        } else {
            let root = this;
            root.setState({
                headline: '',
                details: '',
                Rbnotice: '',

            });
            const params = {
                logo: this.state.Rbnotice === 1 ? "https://cnd2.yeseesports.com//file/2019070203.png" :
                    (this.state.Rbnotice === 2 ? "https://cnd2.yeseesports.com//file/2019070205.png"
                        : "https://cnd2.yeseesports.com//file/2019070206.png"),
                noticeType: this.state.Rbnotice ? this.state.Rbnotice : 0,
                title: this.state.headline,
                content: this.state.details,
            };
            dispatch({
                type: 'CreateNotice/CreateNotice1',
                payload: params,
                callback: response => {
                    if (response.success === true) {
                        console.log('__________成功')
                        message.success('创建成功');
                        this.setState({
                            visible: false
                        })
                        form.validateFields((err, fieldsValue) => {
                            if (err) return;
                            const values = {
                                ...fieldsValue,
                                status,
                                updatedAt: fieldsValue.updatedAt && fieldsValue.updatedAt.valueOf(),
                            };
                            this.setState({
                                formValues: values,
                            });
                            dispatch({
                                type: 'pagednotice/pagednotice1',
                                payload: values,
                            });
                        });
                    }
                }
            });
        }
    }
    handleCancel = e => {
        let root = this;
        root.setState({
            headline: '',
            details: '',
            Rbnotice: 0,
            visible: false
        });
        console.log(e)
    }
    handleSearch1 = e => {
        this.setState({
            Rbnotice: e.target.value
        })
        // this.state.Rbnotice = e.target.value
        console.log(this.state.Rbnotice)
    };


    onChangedetails(e) {
        this.setState({
            details: e.target.value
        })
        console.log(this.state.details)
    }
    onChangeheadline(e) {
        this.setState({
            headline: e.target.value
        })

        console.log(this.state.headline)
    }
    renderForm() {
        const { expandForm } = this.state;
    }
    onShowSizeChange = (current, pageSize) => {
        const { dispatch, form } = this.props;
        const { status } = this.state;
        form.validateFields((err, fieldsValue) => {
            if (err) return;
            const values = {
                skipCount: (current - 1) * pageSize,
                maxResultCount: pageSize,
                ...fieldsValue,
                status,
                updatedAt: fieldsValue.updatedAt && fieldsValue.updatedAt.valueOf(),
            };
            this.setState({
                formValues: values,
            });
            dispatch({
                type: 'pagednotice/pagednotice1',
                payload: values,
            });
        });

    }


    render() {
        const {
            currentUser,
            currentUserLoading,
            pagednotice: { data },
            loading,
        } = this.props;

        const { selectedRows, status } = this.state;

        const pageHeaderContent =
            currentUser && Object.keys(currentUser).length ? (
                <div className={styles.pageHeaderContent}>
                    <div className={styles.avatar}>
                        <Avatar size="large" src={currentUser.avatar} />
                    </div>
                    <div className={styles.content}>
                        <div className={styles.contentTitle}>
                            您好，
              {currentUser.name}
                            ，祝你开心每一天！
            </div>
                    </div>
                </div>
            ) : null;
        return (
            <PageHeaderWrapper
                loading={currentUserLoading}
                content={pageHeaderContent}
            >

                <Card bordered={false}>
                    <Button type="primary" onClick={this.handleCreate}>
                        <Icon type="plus" /> 新建公告
                    </Button>
                    <Divider style={{ marginBottom: 32 }} />
                    <div className={styles.tableList}>
                        <div className={styles.tableListForm}>{this.renderForm()}</div>
                        <Fragment >
                            <StandardTable
                                style={this.state.widowflag}
                                selectedRows={selectedRows}
                                data={data}
                                columns={this.columns}
                                onSelectRow={this.handleSelectRows}
                                onChange={this.handleStandardTableChange}
                            />
                        </Fragment>

                    </div>
                </Card>
                <Modal
                    title={this.state.notice}
                    width={800}
                    visible={this.state.visible}
                    onOk={this.handleOk}
                    onCancel={this.handleCancel}
                >
                    <p>标题 <Input size="large" onChange={this.onChangeheadline.bind(this)} value={this.state.headline} placeholder="请填写您的公告标题" /></p>
                    <p>内容  <TextArea
                        onChange={this.onChangedetails.bind(this)} value={this.state.details}
                        placeholder="请填写您的公告内容"
                        autosize={{ minRows: 4, maxRows: 10 }}
                    /></p>
                    <p>广告类型 <Radio.Group onChange={this.handleSearch1} value={this.state.Rbnotice}>
                        <Radio value={0}>优惠</Radio>
                        <Radio value={1}>提醒</Radio>
                        <Radio value={2}>消息</Radio>
                    </Radio.Group></p>
                </Modal>
            </PageHeaderWrapper>
        );
    }
}

export default pagednotice;